<template>
	<view class="article_reader y-flex" :style="{'background-color': skinColor.color_bg_1}">
		<com-nav-bar border
		:bg-color="skinColor.color_bg_1"
		:color="skinColor.color_2"
		:border-color="skinColor.color_gap_1"
		:title="detail.title" :custom-back="isSaveRecord"></com-nav-bar>
		<view class="y-flex-1 position-relative">
			<scroll-view scroll-y class="position-absolute-cover" @scrolltolower="handleLoadmore">
				<view class="y-flex y-align-center y-justify-center pt-20 pb-20 page-padding-gap"
				v-if="recordCurrent > 1"
				:style="{'background-color': skinColor.color_theme_1}">
					<text class="fs-24" :style="{color: skinColor.color_4}">从上次看到的第{{recordCurrent}}页开始加载</text>
				</view>
				<view class="y-flex pt-30 pb-20 pl-30 pr-30 border-bottom-1 border-bottom-style-dashed"
				v-for="(item, index) in list"
				:style="{'border-color': skinColor.color_gap_1}">
					<view class="y-flex y-row y-align-center">
						<com-avatar size="60" class="mr-20" lazy-load :src="item.avatar" v-if="item.avatar"></com-avatar>
						<view class="y-flex y-justify-between y-flex-1" v-if="item.title">
							<com-text :size="26" :color="skinColor.color_1" :lines="1" :value="item.title" @click="handleTitleTap(item)" />
							<com-text class="mt-10" :size="20" :color="skinColor.color_2" :lines="1" :value="item.subtitle" v-if="item.subtitle" />
						</view>
						<text class="fs-28" :style="{color: skinColor.color_3}">#{{index+1}}</text>
					</view>
					<mp-html class="mt-20" lazy-load selectable preview-img :show-img-menu="false" :copy-link="false" :content="parseContent(item.content)" @linktap="handleLinkTap"></mp-html>
				</view>
				<com-loadmore
				class="mt-30 mb-30"
				:color="skinColor.color_3" :state="loading ? 'loading' : loadmore" @loadmore="handleLoadmore"></com-loadmore>
			</scroll-view>
		</view>
		<com-dialog ref="dialog" />
	</view>
</template>

<script>
	import { openDB, closeDB, select, insert, update, remove } from '@/assets/database'
	import appMixin from '@/assets/mixin/app.js'
	export default {
		mixins: [appMixin],
		computed: {
			history () {
				return this.$store.getters['setting/GET_HISTORY']
			},
			network () {
				return this.$store.getters['network/GET']
			}
		},
		data () {
			return {
				list: [],//列表
				page: 1,
				loadmore: '',
				nextUrl: '',
				recordCurrent: 1,//阅读记录页
				loading: true,//加载
				items: {},//分段
				detail: {},//详情
				query: {},//路由参数
				init: -1//通知渲染层初始化完毕
			}
		},
		mounted () {
			this.items = this.$Route.query.items
			this.detail = this.$Route.query.detail
			this.query = this.$Route.query.query
			this.page = parseInt(this.$Route.query.current)
			this.recordCurrent = this.page
			this.initItems()
		},
		onBackPress(event) {
			if ( event.from == 'backbutton' ) {
				if ( this.$refs.dialog.modal.show ) {
					this.$refs.dialog.modal.show = false
					return true
				}
				return this.isSaveRecord()
			}
			return false
		},
		methods: {
			isSaveRecord () {
				if ( this.detail.uniqueId ) {
					if ( this.history == 0 ) {
						this.$refs.dialog.confirm({
							title: '记录提示',
							content: '当前看到第' + this.page + '页\n\n是否记录位置',
							cancelText: '取消记录',
							confirmText: '保存记录',
							success: res => {
								if ( res.confirm ) {
									this.saveRecord()
								} else {
									uni.navigateBack()
								}
							}
						})
					} else if ( this.history == 1 ) this.saveRecord()
					else uni.navigateBack()
					return true
				}
				return false
			},
			async saveRecord () {
				await openDB()
				try{
					const data = await select('record', 'unique_id = "' + this.detail.uniqueId + '"')
					const record = data.list[0] || {}
					if ( record.id ) {
						await update('record', {
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							current: this.page,
							current_title: '第' + this.page + '页',
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						}, 'id = ' + record.id)
					} else {
						await insert('record', {
							unique_id: this.detail.uniqueId,
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							current: this.page,
							current_title: '第' + this.page + '页',
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						})
					}
					closeDB()
					uni.navigateBack()
				}catch(e){
					closeDB()
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 500)
				}
			},
			handleLinkTap (e) {
				this.navigate(e.href)
			},
			handleTitleTap (item) {
				this.navigate(item.url)
			},
			navigate (url) {
				const pages = getCurrentPages()
				const index = pages.findIndex(page => page.route == 'pages/find/index')
				if ( index > -1 ) {
					const page = pages[index]
					page.$vm.navigate && page.$vm.navigate(url)
				} else {
					uni.showToast({
						title: '无法跳转，请检查是否正确启动了当前应用',
						icon: 'none'
					})
				}
			},
			async initItems () {
				this.loadmore = ''
				try{
					const list = await this.handleGetItems()
					this.list = list
					if ( list.length == 0 ) this.loadmore = 'end'
				}catch(e){
					this.list = []
					this.loadmore = 'end'
				}
				this.loading = false
			},
			async handleLoadmore () {
				if ( ['loading', 'end'].includes(this.loadmore) ) return
				this.loadmore = 'loading'
				this.page++
				try{
					const list = await this.handleGetItems()
					if ( !this.loadmore ) return
					const _isContained = this.$utils.isContained(this.list, list)
					if ( _isContained || list.length == 0 ) {
						this.loadmore = 'end'
						this.page--
					} else {
						this.list = this.list.concat(list)
						this.loadmore = ''
					}
				}catch(e){
					this.loadmore = 'end'
					this.page--
				}
			},
			async handleGetItems () {
				const items = this.items || {}
				const params = Object.assign({}, this.query, this.detail, {page: this.page, list: this.list})
				const staticData = items.staticData ? await this.network.staticDataHandle(items.staticData, params) : []
				const dynamicData = items.dynamicData
				const request = items.request
				let list = []
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, params)
					const response = await this.network.$request(this.nextUrl ? Object.assign({}, newRequest, {url: this.nextUrl}) : newRequest)
					this.nextUrl = newRequest.nextUrl ? await this.network.$text(newRequest.nextUrl, response.data, response.taskId) : ''
					if ( response.data ) list = await this.network.$list(dynamicData, response.data, response.taskId)
				}
				//筛选拥有content内容的项
				return staticData.concat(list).filter(item => item.content)
			},
			parseContent (content) {
				return content ? `<div style="color: ${this.skinColor.color_1}">` + content + '</div>' : ''
			}
		}
	}
</script>

<style>
	.article_reader {
		height: 100%;
	}
</style>